package com.vpen.netty.demo.web.controller;

import cn.hutool.core.util.RandomUtil;
import com.vpen.clib.result.CResult;
import io.netty.util.HashedWheelTimer;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.websocket.server.PathParam;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

/**
 * 描述
 *
 * @author 韦鹏
 * @date 2022/11/13 13:27
 */
@Slf4j
@RestController
@RequestMapping("/")
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class OrderController {

    private final HashedWheelTimer orderTimer;


    @GetMapping("create")
    public CResult<String> crateOrder() {
        String orderNo = RandomUtil.randomString("ABCDEFJHIJKLMNOPQRSTUV", 12);
        log.debug("创建订单：{}", orderNo);

        createTime(orderNo);
        return CResult.success(orderNo);
    }

    public void createTime(String orderNo) {
        //  任务到期需要使用其它线程执行
        orderTimer.newTimeout(timeout -> runAsync(orderNo), 10, TimeUnit.SECONDS);
    }

    /**
     * 异步
     */
    private void runAsync(String orderNo) {
        CompletableFuture.runAsync(() -> {
            log.debug("查询订单是否支付");
            if (RandomUtil.randomBoolean()) {
                log.debug("{},已经支付", orderNo);
                return;
            }
            log.debug("{}订单超时，自动取消订单....", orderNo);
        });
    }

    /**
     * 同步
     */
    private void runSync(String orderNo) {
        log.debug("查询订单是否支付");
        if (RandomUtil.randomBoolean()) {
            log.debug("{},已经支付", orderNo);
            return;
        }
        log.debug("{}订单超时，自动取消订单....", orderNo);

    }

}
